package com.kecheng.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.kecheng.hibernate.BaseDao;import com.kecheng.pojo.Post;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class PostDao extends BaseDao{

	public void add(Post post) {
		this.getHibernateTemplate().save(post);
	}

	public void delete(Post post) {
		this.getHibernateTemplate().delete(post);
	}

	public void update(Post post) {
		this.getHibernateTemplate().merge(post);
		
	}

	public List<Post> findall(int page) {
		int count=10;
        DetachedCriteria criteria=DetachedCriteria.forClass(Post.class);
		criteria.addOrder(Order.desc("id"));
		List<Post> posts= (List<Post>) this.getHibernateTemplate().findByCriteria(criteria, (page-1)*count, count);
		return posts;
	}

	public Post findbyid(int id1) {
		List<Post> posts= (List<Post>) this.getHibernateTemplate().find("from Post where id=?",id1);
		if(posts.size()>0){  
			Post post=posts.get(0);
			return post;
		}
		return null;
		
	}

	public int findallpage() {
		
		String hql = "select count(*) from Post as post";

		Long count = (Long)getHibernateTemplate().find(hql).listIterator().next();
        System.out.println(count);
        int count1=count.intValue();
        int pageSize=10;
        if(count1 % pageSize == 0) {
			return count1/pageSize;
		} else {
			return count1/pageSize+1;
		}
		
	}

	public int findnum() {
		String hql = "select count(*) from Post as post";

		Long count = (Long) getHibernateTemplate().find(hql).listIterator().next();
		int a=new Long(count).intValue();
		return a;
	}

	public List<Post> findall() {
		 DetachedCriteria criteria=DetachedCriteria.forClass(Post.class);
			criteria.addOrder(Order.desc("id"));	
			List<Post> posts= (List<Post>) this.getHibernateTemplate().findByCriteria(criteria);
			return posts;
	}

}
